package com.dji.sample.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dji.sample.common.util.ThumbnailUtil;
import com.dji.sample.component.oss.model.OssConfiguration;
import com.dji.sample.component.oss.service.impl.OssServiceContext;
import com.dji.sample.manage.model.dto.DeviceDictionaryDTO;
import com.dji.sample.manage.service.IDeviceDictionaryService;
import com.dji.sample.media.dao.IFileMapper;
import com.dji.sample.media.model.MediaFileDTO;
import com.dji.sample.media.model.MediaFileEntity;
import com.dji.sample.media.model.OriginalPhotoDTO;
import com.dji.sample.media.service.IFileService;
import com.dji.sample.wayline.dao.IWaylineJobMapper;
import com.dji.sample.wayline.model.dto.WaylineJobDTO;
import com.dji.sample.wayline.model.entity.WaylineJobEntity;
import com.dji.sample.wayline.model.enums.WaylineJobStatusEnum;
import com.dji.sample.wayline.service.IWaylineJobService;
import com.dji.sample.wayline.service.impl.WaylineJobServiceImpl;
import com.dji.sdk.cloudapi.device.DeviceEnum;
import com.dji.sdk.cloudapi.media.MediaSubFileTypeEnum;
import com.dji.sdk.cloudapi.media.MediaUploadCallbackRequest;
import com.dji.sdk.common.Pagination;
import com.dji.sdk.common.PaginationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.net.URL;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * @author sean
 * @version 0.2
 * @date 2021/12/9
 */
@Slf4j
@Service
@Transactional
public class FileServiceImpl implements IFileService {

    @Autowired
    private IFileMapper mapper;

    @Autowired
    private IDeviceDictionaryService deviceDictionaryService;

    @Autowired
    private OssServiceContext ossService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IWaylineJobMapper waylineJobMapper;

    @Autowired
    private ThumbnailUtil thumbnailUtil;

    @Autowired
    @Qualifier("thumbnailExecutor")
    private Executor thumbnailExecutor;

    private String thirdApiUrl = "http://localhost:9022/api/original-photo";

    private Optional<MediaFileEntity> getMediaByFingerprint(String workspaceId, String fingerprint) {
        MediaFileEntity fileEntity = mapper.selectOne(new LambdaQueryWrapper<MediaFileEntity>()
                .eq(MediaFileEntity::getWorkspaceId, workspaceId)
                .eq(MediaFileEntity::getFingerprint, fingerprint));
        return Optional.ofNullable(fileEntity);
    }

    private Optional<MediaFileEntity> getMediaByFileId(String workspaceId, String fileId) {
        MediaFileEntity fileEntity = mapper.selectOne(new LambdaQueryWrapper<MediaFileEntity>()
                .eq(MediaFileEntity::getWorkspaceId, workspaceId)
                .eq(MediaFileEntity::getFileId, fileId));
        return Optional.ofNullable(fileEntity);
    }

    @Override
    public Boolean checkExist(String workspaceId, String fingerprint) {
        return this.getMediaByFingerprint(workspaceId, fingerprint).isPresent();
    }

    @Override
    public Integer saveFile(String workspaceId, MediaUploadCallbackRequest file) {
        MediaFileEntity fileEntity = this.fileUploadConvertToEntity(file);
        fileEntity.setShootPositionLa(file.getMetadata().getShootPosition().getLat());
        fileEntity.setShootPositionLo(file.getMetadata().getShootPosition().getLng());
        fileEntity.setWorkspaceId(workspaceId);
        fileEntity.setFileId(UUID.randomUUID().toString());
        String jobId = fileEntity.getJobId();
        WaylineJobEntity waylineJobEntity = waylineJobMapper.selectOne(new LambdaQueryWrapper<WaylineJobEntity>()
                .eq(WaylineJobEntity::getJobId, jobId));
        if (waylineJobEntity == null) {
            String mediaPath = fileEntity.getFilePath();
            String waylineName = mediaPath.substring(mediaPath.lastIndexOf("-") + 1, mediaPath.length());
            log.info("这个jobId不存在，将要新建一个jobId");
            WaylineJobEntity jobEntity = WaylineJobEntity.builder()
                    .name(waylineName + UUID.randomUUID())
                    .dockSn("")
                    .fileId("")
                    .username("")
                    .workspaceId("")
                    .jobId(UUID.randomUUID().toString())
                    .beginTime(0l)
                    .endTime(0l)
                    .status(WaylineJobStatusEnum.SUCCESS.getVal())
                    .taskType(0)
                    .waylineType(0)
                    .outOfControlAction(0)
                    .rthAltitude(0)
                    .mediaCount(0)
                    .build();
            int insert = waylineJobMapper.insert(jobEntity);
            if (insert<=0) {
                log.error("新建航线任务失败");
            }
        }
        int insert = 0;
        if (!jobId.isEmpty()) {
            insert = mapper.insert(fileEntity);
        }
        return insert;
    }

    @Override
    public List<MediaFileDTO> getAllFilesByWorkspaceId(String workspaceId) {
        return mapper.selectList(new LambdaQueryWrapper<MediaFileEntity>()
                        .eq(MediaFileEntity::getWorkspaceId, workspaceId))
                .stream()
                .map(this::entityConvertToDto)
                .collect(Collectors.toList());
    }

    @Override
    public PaginationData<MediaFileDTO> getMediaFilesPaginationByWorkspaceId(String workspaceId, long page, long pageSize) {
        Page<MediaFileEntity> pageData = mapper.selectPage(
                new Page<MediaFileEntity>(page, pageSize),
                new LambdaQueryWrapper<MediaFileEntity>()
                        .eq(MediaFileEntity::getWorkspaceId, workspaceId)
                        .orderByDesc(MediaFileEntity::getId));
        List<MediaFileDTO> records = pageData.getRecords()
                .stream()
                .map(this::entityConvertToDto)
                .collect(Collectors.toList());

        return new PaginationData<MediaFileDTO>(records, new Pagination(pageData.getCurrent(), pageData.getSize(), pageData.getTotal()));
    }

    @Override
    public URL getObjectUrl(String workspaceId, String fileId) {
        Optional<MediaFileEntity> mediaFileOpt = getMediaByFileId(workspaceId, fileId);
        if (mediaFileOpt.isEmpty()) {
            throw new IllegalArgumentException("{} doesn't exist.");
        }

        return ossService.getObjectUrl(OssConfiguration.bucket, mediaFileOpt.get().getObjectKey());
    }

    @Override
    public List<MediaFileDTO> getFilesByWorkspaceAndJobId(String workspaceId, String jobId) {
        return mapper.selectList(new LambdaQueryWrapper<MediaFileEntity>()
                        .eq(MediaFileEntity::getWorkspaceId, workspaceId)
                        .eq(MediaFileEntity::getJobId, jobId))
                .stream()
                .map(this::entityConvertToDto).collect(Collectors.toList());
    }

    @Override
    public PaginationData<MediaFileEntity> getMediaFileEntitiesPaginationByWorkspaceId(String workspaceId, long page, long pageSize) {
        Page<MediaFileEntity> pageData = mapper.selectPage(
                new Page<MediaFileEntity>(page, pageSize),
                new LambdaQueryWrapper<MediaFileEntity>()
                        .eq(MediaFileEntity::getWorkspaceId, workspaceId)
                        .orderByDesc(MediaFileEntity::getId));

        return new PaginationData<MediaFileEntity>(pageData.getRecords(), new Pagination(pageData.getCurrent(), pageData.getSize(), pageData.getTotal()));
    }

    /**
     * Convert the received file object into a database entity object.
     *
     * @param file
     * @return
     */
    private MediaFileEntity fileUploadConvertToEntity(MediaUploadCallbackRequest file) {
        MediaFileEntity.MediaFileEntityBuilder builder = MediaFileEntity.builder();

        if (file != null) {
            builder.fileName(file.getName())
                    .filePath(file.getPath())
                    .fingerprint(file.getFingerprint())
                    .objectKey(file.getObjectKey())
                    .subFileType(Optional.ofNullable(file.getSubFileType()).map(MediaSubFileTypeEnum::getType).orElse(null))
                    .isOriginal(file.getExt().getOriginal())
                    .jobId(file.getExt().getFileGroupId())
                    .drone(file.getExt().getSn())
                    .tinnyFingerprint(file.getExt().getTinnyFingerprint())
                    .payload(file.getExt().getPayloadModelKey().getDevice());

            // domain-type-subType
            DeviceEnum payloadModelKey = file.getExt().getPayloadModelKey();
            Optional<DeviceDictionaryDTO> payloadDict = deviceDictionaryService
                    .getOneDictionaryInfoByTypeSubType(payloadModelKey.getDomain().getDomain(),
                            payloadModelKey.getType().getType(), payloadModelKey.getSubType().getSubType());
            payloadDict.ifPresent(payload -> builder.payload(payload.getDeviceName()));
        }
        return builder.build();
    }

    @Override
    public MediaFileDTO getFileByFileId(String workspaceId, String fileId) {
        Optional<MediaFileEntity> fileEntityOpt = getMediaByFileId(workspaceId, fileId);
        return fileEntityOpt.map(this::entityConvertToDto).orElse(null);
    }

    @Override
    public PaginationData<MediaFileEntity> queryMediaFileEntitiesPaginationByWorkspaceId(String workspaceId, String droneSn, String waylineId, long startTime, long endTime, long page, long pageSize) {
        List<String> jobIds = null;

        if (waylineId != null && !waylineId.isEmpty()) {
//            List<WaylineJobDTO> waylineJobDTOS = waylineJobService.getJobsByWaylineId(waylineId);

            List<WaylineJobEntity> waylineJobEntities = waylineJobMapper.selectList(
                    new LambdaQueryWrapper<WaylineJobEntity>()
                            .eq(WaylineJobEntity::getFileId, waylineId)
            );
            jobIds = waylineJobEntities.stream()
                    .map(WaylineJobEntity::getJobId)
                    .collect(Collectors.toList());
        }

        LambdaQueryWrapper<MediaFileEntity> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(MediaFileEntity::getWorkspaceId, workspaceId);

        if (droneSn != null && !droneSn.isEmpty()) {
            queryWrapper.eq(MediaFileEntity::getDrone, droneSn);
        }

        if (jobIds != null && !jobIds.isEmpty()) {
            queryWrapper.in(MediaFileEntity::getJobId, jobIds);
        }

        if (startTime > 0) {
            queryWrapper.ge(MediaFileEntity::getCreateTime, startTime);
        }

        if (endTime > 0) {
            queryWrapper.le(MediaFileEntity::getCreateTime, endTime);
        }

//        if(type != null && !type.isEmpty()) {
//            queryWrapper.like(MediaFileEntity::getFileName,"%"+type+"%");
//        }else{
//            queryWrapper.like(MediaFileEntity::getFileName,"%V_%");
//        }

        queryWrapper.orderByDesc(MediaFileEntity::getId);

        Page<MediaFileEntity> pageData = mapper.selectPage(new Page<>(page, pageSize), queryWrapper);

        return new PaginationData<>(pageData.getRecords(), new Pagination(pageData.getCurrent(), pageData.getSize(), pageData.getTotal()));
    }

    /**
     * Convert database entity objects into file data transfer object.
     *
     * @param entity
     * @return
     */
    private MediaFileDTO entityConvertToDto(MediaFileEntity entity) {
        MediaFileDTO.MediaFileDTOBuilder builder = MediaFileDTO.builder();

        if (entity != null) {
            builder.fileName(entity.getFileName())
                    .fileId(entity.getFileId())
                    .filePath(entity.getFilePath())
                    .isOriginal(entity.getIsOriginal())
                    .fingerprint(entity.getFingerprint())
                    .objectKey(entity.getObjectKey())
                    .tinnyFingerprint(entity.getTinnyFingerprint())
                    .payload(entity.getPayload())
                    .createTime(LocalDateTime.ofInstant(
                            Instant.ofEpochMilli(entity.getCreateTime()), ZoneId.systemDefault()))
                    .drone(entity.getDrone())
                    .jobId(entity.getJobId());

        }

        return builder.build();
    }

}
